/**
 * 防抖  某个函数在某段时间内，无论触发了多少次回调，都只执行最后一次
 * @param {Function} func
 * @param {Number} wait
 * @param {Boolean} immediate 是否立即调用
 * @return {*}
 */
export function debounce(func, wait, immediate) {
  let timer
  return function (...args) {
    if (timer) clearTimeout(timer)
    if (immediate) {
      const callNow = !timer
      timer = setTimeout(() => {
        timer = null
      }, wait)
      if (callNow) func.apply(this, args)
    } else {
      timer = setTimeout(() => {
        func.apply(this, args)
      }, wait)
    }
  }
}

/**
 * 节流  某个函数在一段时间内只触发第一次，过了时间后才可以再次触发
 * @param {Function} func
 * @param {Number} wait
 */
export function throttle(func, wait) {
  let timer
  let last = 0
  return function (...args) {
    if (timer) clearTimeout(timer)
    const now = +new Date()
    if (now - last >= wait) {
      func.apply(this, args)
      last = now
    } else {
      timer = setTimeout(() => {
        last = now
        func.apply(this, args)
      }, wait)
    }
  }
}
